package com.suning.sawp.service.impl.assistant;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.reflect.TypeToken;
import com.suning.framework.dal.client.DalClient;
import com.suning.framework.sedis.JedisAction;
import com.suning.framework.sedis.JedisClient;
import com.suning.rsf.provider.annotation.Implement;
import com.suning.sawp.dto.common.QueryResult;
import com.suning.sawp.intf.assistant.ClientVersionManageService;
import com.suning.sawp.po.assistant.ClientVersionManage;
import com.suning.sawp.remote.intf.IVersion;
import com.suning.sawp.service.util.GsonUtils;

import redis.clients.jedis.Jedis;

@Implement(contract = IVersion.class, implCode = "iVersion")
@Service
public class ClientVersionManageServiceImpl implements ClientVersionManageService, IVersion {

    @Autowired
    DalClient dalClient;
    
    @Resource
    JedisClient jedisClient;
    
    private static final String CLIENT_VERSION_CACHE = "com.suning.client.versonManage";
    @Override
    public QueryResult<ClientVersionManage> query(Long id, int pageNo, int pageSize) {
        QueryResult<ClientVersionManage> queryResult = new QueryResult<ClientVersionManage>();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("id", id);
        // 查询总记录数
        int totalSize = dalClient.queryForObject("VERSION_MANAGE.COUNT_ALL_VERSION", paramMap, Integer.class);
        paramMap.put("startIndex", (pageNo < 1 ? 1 : pageNo - 1) * pageSize);
        paramMap.put("limit", pageSize);
        List<ClientVersionManage> records = dalClient.queryForList("VERSION_MANAGE.SELECT_ALL_VERSION", paramMap, ClientVersionManage.class);
        queryResult.setTotalSize(totalSize);
        queryResult.setRecords(records);
        return queryResult;
    }

    @Override
    public void editClientVersionManage(ClientVersionManage versionManage) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("switchName", versionManage.getSwitchName());
        paramMap.put("switchTitle", versionManage.getSwitchTitle());
        paramMap.put("switchDetail", versionManage.getSwitchDetail());
        paramMap.put("switchValue", versionManage.getSwitchValue());
        paramMap.put("switchUrl", versionManage.getSwitchUrl());
        paramMap.put("fourceUpdateValue", versionManage.getFourceUpdateValue());
        paramMap.put("diffUpdateValue", versionManage.getDiffUpdateValue());
        paramMap.put("diffUrl", versionManage.getDiffUrl());
        if (null != versionManage.getId()) {
            paramMap.put("id", versionManage.getId());
            // 有ID做更新操作
            dalClient.execute("VERSION_MANAGE.UPDATE_VERSION", paramMap);
        } else {
            // 无ID做删除操作
            dalClient.execute("VERSION_MANAGE.INSERT_VERSION", paramMap);
        }
        jedisClient.execute(new JedisAction<String>() {
            @Override
            public String doAction(Jedis jedis) {
                jedis.del(CLIENT_VERSION_CACHE);
                return null;
            }
            
        });
    }

    @Override
    public void deleteClientVersionManage(Long id) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("id", id);
        dalClient.execute("VERSION_MANAGE.REMOVE_VERSION_BY_ID", paramMap);
        jedisClient.execute(new JedisAction<String>() {
            @Override
            public String doAction(Jedis jedis) {
                jedis.del(CLIENT_VERSION_CACHE);
                return null;
            }
            
        });
    }

    @Override
    public String selectVersion(String appKey) {
        // 1.先查询redis
        String versions = jedisClient.execute(new JedisAction<String>() {

            @Override
            public String doAction(Jedis jedis) {
                String result = jedis.get(CLIENT_VERSION_CACHE);
                // 2.如果redis为空，查询数据库并更新redis
                if (StringUtils.isBlank(result)) {

                    // 2.1查询数据库
                    Map<String, Object> paramMap = new HashMap<String, Object>();
                    List<ClientVersionManage> list = dalClient.queryForList("VERSION_MANAGE.SELECT_ALL_VERSION", paramMap,
                            ClientVersionManage.class);
                    Map<String, List<ClientVersionManage>> resultMap = new HashMap<String, List<ClientVersionManage>>();
                    resultMap.put("switchList", list);
                    result = GsonUtils.toJson(resultMap, true);
                    // 2.2缓存信息
                    jedis.set(CLIENT_VERSION_CACHE, result);
                }
                return result;
            }
        });

        return handleVersionWithKey(appKey, versions);
    }

    private String handleVersionWithKey(String appKey, String versions) {
        // 判断入参是否包含指定app key
        if (StringUtils.isNotBlank(appKey)) {
            Map<String, List<ClientVersionManage>> result = GsonUtils.fromJson(versions,
                    new TypeToken<HashMap<String, List<ClientVersionManage>>>() {
                    });
            List<ClientVersionManage> list = result.get("switchList");

            Iterator<ClientVersionManage> sListIterator = list.iterator();
            while (sListIterator.hasNext()) {
                ClientVersionManage dto = sListIterator.next();
                if (!appKey.equals(dto.getSwitchName())) {
                    sListIterator.remove();
                }
            }
            result.put("switchList", list);
            return GsonUtils.toJson(result, true);
        } else {
            return versions;
        }
    }
}
